#!/usr/bin/env python

from ImgTiler import CombineTiles
import cv2
import os
from fire import Fire
import pyvips


@Fire
def main(dir, scale, row, col, overlap):
    loaded_tiles = []
    overlap = overlap * scale
    tile_files = sorted(os.listdir(dir), key=lambda x: int(x.split(".")[0]))
    print(tile_files)
    for filename in tile_files:
        tile_path = os.path.join(dir, filename)
        tile_img = cv2.imread(tile_path)
        if tile_img is not None:
            loaded_tiles.append(tile_img)

    print(f"从 '{dir}' 目录加载了 {len(loaded_tiles)} 个图块。")
    combiner = CombineTiles(loaded_tiles, (row, col), overlap)
    merged_image = combiner.combine_tiles(show_image=False)
    merged_image = cv2.cvtColor(merged_image, cv2.COLOR_BGR2RGB)

    output_image_path = "merge.tif"
    height, width, bands = merged_image.shape
    vips_image = pyvips.Image.new_from_memory(
        merged_image.data, width, height, bands, "uchar"
    )
    vips_image.write_to_file(output_image_path)
    print(f"合并后的图片已保存到 '{output_image_path}'")
